package com.ipodget

public class Ipod {
	private static final String MUSIC_ROOT = "iPod_Control/Music"
	private static final String INDEX_ROOT = ".ipod-get"
	private static final String ITUNESDB = "iPod_Control/iTunes/iTunesDB"

	File mountPoint
	File itunesDb
	File musicRoot
	File indexRoot
	
	public Ipod(File mountPoint) throws IpodNotFoundException {
		this.mountPoint = mountPoint
		if(!getItunesDb().exists()){
			throw new IpodNotFoundException("Cannot find itunes db!")
		}
	}
	
	public File getItunesDb(){
		if(itunesDb == null){
			itunesDb = new File(mountPoint, ITUNESDB) 
		}
		return itunesDb
	}
	
	public File getMusicRoot(){
		if(musicRoot == null){
			musicRoot = new File(mountPoint, MUSIC_ROOT) 
		}
		return musicRoot
	}

	public File getIndexRoot(){
		if(indexRoot == null){
			indexRoot = new File(mountPoint, INDEX_ROOT) 
		}
		return indexRoot
	}

	def isIndexingNeeded(){
		getItunesDb().lastModified() > getIndexRoot().lastModified()
	}
	
	def index = { logger ->
		def indexer = new IpodIndexer(this)
		indexer.index(logger)
	}
	
	def crawl = { crawler ->
		getMusicRoot().eachFileRecurse crawler
	}
	
	def countMusicFiles = {
		def musicFiles = 0
		this.crawl { file ->
			if (file.name =~ /.mp3$/) {
				musicFiles += 1
			}
		}
		return musicFiles
	}
	
	def search = { searchQuery, logger ->
		def indexSearcher = new IpodIndexSearcher(getIndexRoot())
		indexSearcher.search(searchQuery, logger)
	}
}